package com.googlecode.androidspamblocker;

import java.util.Iterator;
import java.util.List;

import com.googlecode.androidspamblocker.SmsBlocker.SmsBlockerBinder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SmsBlockerActivity extends Activity {
	private static final String TAG = "SmsBlockerActivity";
	private SmsBlocker blocker;
	private boolean fBound = false;
	
	private ServiceConnection sc = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			blocker = ((SmsBlockerBinder)service).getService();
			fBound = true;
			showRules();
		}
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			fBound = false;
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		Intent intent = new Intent(this, SmsBlocker.class);
		bindService(intent, sc, BIND_AUTO_CREATE);
	}
	
	@Override
	public void onStop() {
		super.onStop();
		if(fBound) {
			unbindService(sc);
			fBound = false;
		}
	}
	
	private void showRules() {
		ViewGroup vg = (ViewGroup)findViewById(R.id.lMain);
		if(fBound) {
			List<SmsFilter> filters = ((SmsCustomFilters)blocker.getRuleManager().getPersonalRule()).getFilters();
			Iterator<SmsFilter> iter = filters.iterator();
			while(iter.hasNext()) {
				//tv.append(iter.next().toString() + "\n");
				vg.addView(createFilterView(iter.next()));
			}
		}
	}
	
	private View createFilterView(SmsFilter filter) {
		LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.personalfilter, null);
		((CheckBox)v.findViewById(R.id.cbEnabled)).setChecked(true);
		((TextView)v.findViewById(R.id.tvFilter)).setText(filter.toString());
		return v;
	}

}
